package com.ruoyi.functiontest.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.InterchangeMileageStatTest;
import com.ruoyi.functiontest.service.IInterchangeMileageStatTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 互通里程实测数据测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/functiontest/InterchangeMileageStatTest")
public class InterchangeMileageStatTestController extends BaseController
{
    @Autowired
    private IInterchangeMileageStatTestService interchangeMileageStatTestService;

    /**
     * 查询互通里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeMileageStatTest:list')")
    @GetMapping("/list")
    public AjaxResult list(InterchangeMileageStatTest interchangeMileageStatTest)
    {
        List<InterchangeMileageStatTest> list = interchangeMileageStatTestService.selectInterchangeMileageStatTestList(interchangeMileageStatTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = interchangeMileageStatTest.getRoadName() != null && !interchangeMileageStatTest.getRoadName().isEmpty() ||
                                   interchangeMileageStatTest.getNodeName() != null && !interchangeMileageStatTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<InterchangeMileageStatTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出互通里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeMileageStatTest:export')")
    @Log(title = "互通里程实测数据测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InterchangeMileageStatTest interchangeMileageStatTest)
    {
        List<InterchangeMileageStatTest> list = interchangeMileageStatTestService.selectInterchangeMileageStatTestList(interchangeMileageStatTest);
        // 构建树形结构
        List<InterchangeMileageStatTest> treeList = buildTree(list);
        // 只导出第二层的数据，并将第一层的路段名称存入第二层的路段名称中
        List<InterchangeMileageStatTest> exportList = new ArrayList<>();
        for (InterchangeMileageStatTest parent : treeList) {
            if (parent.getChildren() != null && !parent.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<InterchangeMileageStatTest> children = (List<InterchangeMileageStatTest>) parent.getChildren();
                for (InterchangeMileageStatTest child : children) {
                    // 创建新的对象避免修改原数据
                    InterchangeMileageStatTest exportItem = new InterchangeMileageStatTest();
                    // 复制子节点的所有属性
                    exportItem.setId(child.getId());
                    exportItem.setParentId(child.getParentId());
                    exportItem.setNodeName(child.getNodeName());
                    exportItem.setRamp1Type(child.getRamp1Type());
                    exportItem.setRamp1Length(child.getRamp1Length());
                    exportItem.setRamp2Type(child.getRamp2Type());
                    exportItem.setRamp2Length(child.getRamp2Length());
                    exportItem.setRamp3Type(child.getRamp3Type());
                    exportItem.setRamp3Length(child.getRamp3Length());
                    exportItem.setRamp4Type(child.getRamp4Type());
                    exportItem.setRamp4Length(child.getRamp4Length());
                    exportItem.setRampAvgLength(child.getRampAvgLength());
                    exportItem.setTollCenterLength(child.getTollCenterLength());
                    exportItem.setApproachLength(child.getApproachLength());
                    exportItem.setRemark(child.getRemark());
                    // 将第一层的路段名称存入第二层的路段名称中
                    exportItem.setRoadName(parent.getRoadName());
                    exportList.add(exportItem);
                }
            }
        }
        ExcelUtil<InterchangeMileageStatTest> util = new ExcelUtil<InterchangeMileageStatTest>(InterchangeMileageStatTest.class);
        util.exportExcel(response, exportList, "互通里程实测数据测试数据");
    }

    /**
     * 构建树形结构
     */
    private List<InterchangeMileageStatTest> buildTree(List<InterchangeMileageStatTest> list) {
        // 构建父子关系映射
        Map<Long, InterchangeMileageStatTest> nodeMap = new HashMap<>();
        List<InterchangeMileageStatTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (InterchangeMileageStatTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (InterchangeMileageStatTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                InterchangeMileageStatTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<InterchangeMileageStatTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<InterchangeMileageStatTest> children = (List<InterchangeMileageStatTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }

    /**
     * 获取互通里程实测数据测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeMileageStatTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(interchangeMileageStatTestService.selectInterchangeMileageStatTestById(id));
    }

    /**
     * 新增互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeMileageStatTest:add')")
    @Log(title = "互通里程实测数据测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InterchangeMileageStatTest interchangeMileageStatTest)
    {
        return toAjax(interchangeMileageStatTestService.insertInterchangeMileageStatTest(interchangeMileageStatTest));
    }

    /**
     * 修改互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeMileageStatTest:edit')")
    @Log(title = "互通里程实测数据测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InterchangeMileageStatTest interchangeMileageStatTest)
    {
        return toAjax(interchangeMileageStatTestService.updateInterchangeMileageStatTest(interchangeMileageStatTest));
    }

    /**
     * 删除互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeMileageStatTest:remove')")
    @Log(title = "互通里程实测数据测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (interchangeMileageStatTestService.hasChildById(id)) {
                return AjaxResult.error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(interchangeMileageStatTestService.deleteInterchangeMileageStatTestByIds(ids));
    }
}
